#!/usr/bin/env python 
# coding:utf-8
# @Time :9/11/18 14:38

from common.time_human import TimeHuman

from scheduler.file_config_loader import FileConfigLoader
from scheduler.db_config_loader import DbConfigLoader


# 调度配置动态加载
class ScheduleConfLoader(object):

    __LOAD_CONFIG_PERIOD = 60

    def __init__(self, config_table, source_db, file_path, log):
        self.logger = log
        self.time_human = TimeHuman()
        self.__file_load = FileConfigLoader(file_path, log)
        self.__db_load = DbConfigLoader(config_table, source_db, log)
        self.__last_load_time = self.time_human.now()
        self.__table_config_dict = self.__load_conf()

    # 获取当前配置信息
    def get_config_dict(self):
        current_time = self.time_human.now()
        if current_time - self.__last_load_time >= self.__LOAD_CONFIG_PERIOD:
            self.__table_config_dict = self.__load_conf()
            self.__last_load_time = current_time

        return self.__table_config_dict

    # 加载当前配置信息
    def __load_conf(self):
        table_config_dict = self.__db_load.load_conf()
        if len(table_config_dict) > 0:
            self.__file_load.save_conf(**table_config_dict)
        else:
            table_config_dict = self.__file_load.load_conf()

        return table_config_dict